package com.besall.allbase.bluetooth.scan;

import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.INFO_Unbind_BT;

import java.io.Serializable;
import java.util.ArrayList;

import com.bes.bessdk.connect.BleConnector;
import com.bes.bessdk.connect.SppConnector;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.scan.ScanManager;
import com.bes.sdk.utils.DeviceProtocol;
import com.besall.allbase.bluetooth.BluetoothConstants;
import com.besall.allbase.bluetooth.scan.adapter.DeviceAdapter;
import com.besall.allbase.common.manager.PermissionManager;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.ProtocolPresenter;
import com.besall.allbase.view.base.BaseActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import bb.lanxing.R;

public class ScanActivity extends BaseActivity<IScanActivity, ScanPresenter> implements IScanActivity, SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemClickListener, ScanManager.ScanListener, DeviceAdapter.DeviceItemClickListener {

	private final String TAG = getClass().getSimpleName();
	public DeviceProtocol deviceProtocol;
	SwipeRefreshLayout mSwipeRefresh;
	Handler handler = null;
	boolean onceClick = false;// avoid repeat click
	private ScanActivity instance;
	private boolean isMultipleDevices = false;
	private ListView mDevices;
	private DeviceAdapter mAdapter;
	private Menu mMenu;

	@Override protected ScanPresenter createPresenter() {
		return new ScanPresenter();
	}

	@Override protected void initBeforeSetContent() {
		Intent receiveIntent = getIntent();
		isMultipleDevices = receiveIntent.getBooleanExtra(BluetoothConstants.Scan.BES_SCAN_IS_MULTIPLE_DEVICES, false);
		// 得到Intent
		if (receiveIntent.getIntExtra(BluetoothConstants.Scan.BES_SCAN, 0) == BluetoothConstants.Scan.SCAN_BLE) {
			deviceProtocol = DeviceProtocol.PROTOCOL_BLE;
		} else if (receiveIntent.getIntExtra(BluetoothConstants.Scan.BES_SCAN, 0) == BluetoothConstants.Scan.SCAN_SPP) {
			deviceProtocol = DeviceProtocol.PROTOCOL_SPP;
		} else if (receiveIntent.getIntExtra(BluetoothConstants.Scan.BES_SCAN, 0) == BluetoothConstants.Scan.SCAN_USB) {
			isMultipleDevices = false;
			deviceProtocol = DeviceProtocol.PROTOCOL_USB;
		}
	}

	@Override protected int getContentViewId() {
		return R.layout.act_scan;
	}

	@Override protected void bindView() {
		getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
		mAdapter = new DeviceAdapter(this, deviceProtocol);
		mAdapter.setDeviceItemClickListener(this);
		mDevices = findViewById(R.id.devices);
		mSwipeRefresh = findViewById(R.id.swipe_refresh);
		tv_title = findViewById(R.id.tv_title);
	}

	@Override protected void initView() {
		handler = new Handler();
		mAdapter.setIsMultipleDevices(isMultipleDevices);
		mDevices.setAdapter(mAdapter);
		mDevices.setOnItemClickListener(this);
		mSwipeRefresh.setOnRefreshListener(this);
		inittoolbar("");
		if (deviceProtocol == DeviceProtocol.PROTOCOL_BLE) {
			tv_title.setText(R.string.activity_bluetooth_scan);
		} else if (deviceProtocol == DeviceProtocol.PROTOCOL_SPP) {
			tv_title.setText(R.string.activity_classics_devices_scan);
		} else if (deviceProtocol == DeviceProtocol.PROTOCOL_USB) {
			tv_title.setText(R.string.activity_USB_scan);
		}

		startScan();

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {

		} else {
			PermissionManager.getInstance().requestPermissions(this, null, PermissionManager.Permission.Storage.WRITE_EXTERNAL_STORAGE);
		}

		/*
		 * IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_BES_BLE_CONNECT_STATE);
		 * registerReceiver(connectStatusReceiver,filter);
		 */

	}

	@Override protected void setInstance() {
		instance = this;
	}

	@Override protected void removeInstance() {
		instance = null;
	}

	@Override protected void onDestroy() {
		super.onDestroy();
		stopScan();
	}

	@Override public boolean onOptionsItemSelected(MenuItem item) {
		// swtich to if else
		if (item.getItemId() == android.R.id.home) {
			Log.i(TAG, "onOptionsItemSelected: -------------");
			stopScan();
			if (deviceProtocol != DeviceProtocol.PROTOCOL_USB && !mAdapter.getSelectedDevices().isEmpty() && isMultipleDevices) {
				Intent intent = new Intent();
				intent.putExtra(BluetoothConstants.Scan.BES_SCAN_RESULT, (Serializable) mAdapter.getSelectedDevices());
				setResult(RESULT_OK, intent);
			}
			finish();
		} else if (item.getItemId() == R.id.menu_select_act_scan) {
			if (!mAdapter.getSelectedDevices().isEmpty() && isMultipleDevices) {
				stopScan();
				Intent intent = new Intent();
				intent.putExtra(BluetoothConstants.Scan.BES_SCAN_RESULT, (Serializable) mAdapter.getSelectedDevices());
				setResult(RESULT_OK, intent);
				finish();
			}
		}
		// origin code
		/*
		 * switch (item.getItemId()) {
		 *
		 * case android.R.id.home: Log.i(TAG, "onOptionsItemSelected: -------------"); stopScan(); if (deviceProtocol !=
		 * DeviceProtocol.PROTOCOL_USB && mAdapter.getSelectedDevices().size() > 0 && isMultipleDevices) { Intent intent
		 * = new Intent(); intent.putExtra(BluetoothConstants.Scan.BES_SCAN_RESULT, (Serializable)
		 * mAdapter.getSelectedDevices()); setResult(RESULT_OK, intent); } finish(); break; case
		 * R.id.menu_select_act_scan: if (mAdapter.getSelectedDevices().size() > 0 && isMultipleDevices) { stopScan();
		 * Intent intent = new Intent(); intent.putExtra(BluetoothConstants.Scan.BES_SCAN_RESULT, (Serializable)
		 * mAdapter.getSelectedDevices()); setResult(RESULT_OK, intent); finish(); } break; default: break; }
		 */
		return super.onOptionsItemSelected(item);
	}

	@Override public boolean onCreateOptionsMenu(Menu menu) {
		if (isMultipleDevices) {
			getMenuInflater().inflate(R.menu.menu_select, menu);
			mMenu = menu;
		}
		return true;
	}

	@SuppressLint("RestrictedApi") @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (deviceProtocol == DeviceProtocol.PROTOCOL_USB) {
			Intent intent = new Intent();
			intent.putExtra(BluetoothConstants.Scan.BES_SCAN_RESULT, mAdapter.getItem(position));
			setResult(RESULT_OK, intent);
			finish();
			return;
		}
		Log.d(TAG, " selected the device");
		stopScan();// add by wangsm
		if (isMultipleDevices) {
			mAdapter.addSelectState(position);
			int size = mAdapter.getSelectedDevices().size();
			MenuItem item = mMenu.findItem(R.id.menu_select_act_scan);
			item.setIcon(size == 0 ? R.drawable.ota_top_nor : R.drawable.ota_top_sele);
		} else {
			mAdapter.addSelectState(position);
			Intent intent = new Intent();
			intent.putExtra(BluetoothConstants.Scan.BES_SCAN_RESULT, mAdapter.getItem(position));
			setResult(RESULT_OK, intent);
			finish();
		}
	}

	@Override public void onRefresh() {
		if (mAdapter != null) {
			mAdapter.clear();
			if (isMultipleDevices) {
				MenuItem item = mMenu.findItem(R.id.menu_select_act_scan);
				item.setIcon(R.drawable.ota_top_nor);
			}
		}
		Log.d(TAG, "  onRefresh: start scan");
		startScan();
	}

	@Override public void onScanResult(HmDevice scannedDevice) {
		addDevice(scannedDevice, false);
	}

	private void addDevice(HmDevice hmDevice, boolean before) {
		if (before) {
			mAdapter.addBefore(hmDevice, hmDevice.getRssi());
		} else {
			mAdapter.add(hmDevice, hmDevice.getRssi());
		}
	}

	@Override public void onDeviceOffline(HmDevice device) {

	}

	@Override public void onScanFailed(String message) {
		Log.d(TAG, " scan ble fail,message: " + message);
		startScan();
	}

	private static final long SCAN_PERIOD = 10000; // 10 seconds

	private void startScan() {
		Log.i(TAG, "startScan: ----------1111111111");
		if (mAdapter != null) {
			mAdapter.clear();
		}
		if (deviceProtocol == DeviceProtocol.PROTOCOL_USB) {
			mPresenter.starScanWithScanType(instance, deviceProtocol);
			return;
		}
		ArrayList<HmDevice> curConSppDevices = SppConnector.getsConnector(instance, null).getCurConnectDevices();
		for (int i = 0; i < curConSppDevices.size(); i++) {
			HmDevice hmDevice = curConSppDevices.get(i);
			//            hmDevice.setRssi(1000);
			addDevice(hmDevice, true);
		}
		ArrayList<HmDevice> curConBleDevices = BleConnector.getsConnector(instance, null, null).getCurConnectDevices();
		for (int i = 0; i < curConBleDevices.size(); i++) {
			HmDevice hmDevice = curConBleDevices.get(i);
			//            hmDevice.setRssi(1000);
			addDevice(hmDevice, true);
		}
		Log.d(TAG, " scan activity begin scan");
		if (instance != null) {
			mPresenter.starScanWithScanType(instance, deviceProtocol);
			Log.d(TAG, " post delay stop");
			new Handler().postDelayed(this::stopScan, SCAN_PERIOD);
		}

		// mPresenter.starScanWithScanType(instance, deviceProtocol);
	}

	private void stopScan() {
		Log.d(TAG, "  stop scan");
		mPresenter.stopScanWithScanType(instance, deviceProtocol);
		if (mSwipeRefresh != null) {
			mSwipeRefresh.setRefreshing(false);
		}
	}

	@Override public void unbindDevice() {
		ProtocolPresenter protocolPresenter = ProtocolPresenter.getInstance();
		ArrayList<HmDevice> curConBleDevices = BleConnector.getsConnector(this, null, null).getCurConnectDevices();
		Log.d(TAG, " unbind the device click ,onceClick: " + onceClick);
		if (protocolPresenter != null && curConBleDevices != null && !curConBleDevices.isEmpty() && !onceClick) {
			onceClick = true;
			Log.d(TAG, " unbind the device click ,onceClick: " + onceClick);
			protocolPresenter.sendInfoData(INFO_Unbind_BT, null);
			finish();
		}
	}
	/*
	 * BroadcastReceiver connectStatusReceiver = new BroadcastReceiver() {
	 *
	 * @Override public void onReceive(Context context, Intent intent) { //Log.d(TAG,
	 * " the connectStatusReceiver ,action:" + intent.getAction() + " state: " + intent.getIntExtra("conn_state",
	 * BesSdkConstants.BES_CONNECT_ERROR)); String action = intent.getAction();
	 * if(ACTION_BES_BLE_CONNECT_STATE.equals(action)){ int state = intent.getIntExtra("conn_state",
	 * BesSdkConstants.BES_CONNECT_ERROR); Log.d(TAG, " the connectStatusReceiver , state: " + state); if(state ==
	 * BesSdkConstants.BES_CONNECT_ERROR){ // startScan();
	 *//*
	 * ArrayList<HmDevice> curConBleDevices = BleConnector.getsConnector(instance, null,
	 * null).getCurConnectDevices(); for (int i = 0; i < curConBleDevices.size(); i ++) { HmDevice hmDevice =
	 * curConBleDevices.get(i); hmDevice.setRssi(1000); addDevice(hmDevice, true); }
	 *//*
	 *//*
	 * if(mAdapter != null){ mAdapter.notifyDataSetChanged(); }
	 *//*
	 * }
	 *
	 * } } };
	 */
}
